import axios from "axios";
import setting from "@/settings";
import {
  getToken,
  getExpiredStatus
} from "@/utils/auth";
import {
  refreshToken,
  handleRefreshFail
} from "@/utils/refresh.js";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
});

// request interceptor

service.interceptors.request.use(
  async (config) => {
      // 判断是否过期 未过期
      let Auth = `Bearer ${getToken()}`;
      const isExpired = getExpiredStatus();

      // 获取上次刷新token的时间
      const lastRefreshTime = localStorage.getItem('lastRefreshTime') || Date.now();
      const now = Date.now();
      console.log(lastRefreshTime, "上次的token时间");
      const thirtyMinutes = 10 * 60 * 1000;

      // 如果距离上次刷新超过30分钟，或token已过期，则刷新token
      if (isExpired) {
        try {
          console.log('刷新token');
          await refreshToken();
          Auth = `Bearer ${getToken()}`;
          // 更新刷新时间
          localStorage.setItem('lastRefreshTime', Date.now());
        } catch (e) {
          handleRefreshFail();
        }
      }
      config.headers["Authorization"] = Auth;

      if (setting.isWebsocket) {
        config.headers['X-Socket-Id'] = window.localStorage.getItem('uuid')
      }
      return config;
    },
    (error) => {
      // do something with request error
      return Promise.reject(error);
    }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  (response) => {
    const res = response.data;
    return res;
  },
  (error) => {
    console.log("err" + error); // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error);
  }
);

export default service;
